package com.hu.system.service.impl;

import java.util.List;
import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.hu.common.utils.SecurityUtils;
import com.hu.system.mapper.StockReturnMapper;
import com.hu.system.mapper.StockInboundMapper;
import com.hu.system.mapper.StockOutboundMapper;
import com.hu.system.mapper.SysUserShopMapper;
import com.hu.system.domain.StockReturn;
import com.hu.system.domain.StockInbound;
import com.hu.system.domain.StockOutbound;
import com.hu.system.service.IStockReturnService;

/**
 * 退货入库Service业务层处理
 *
 * @author hu
 * @date 2025-01-22
 */
@Service
public class StockReturnServiceImpl implements IStockReturnService {
    @Autowired
    private StockReturnMapper stockReturnMapper;

    @Autowired
    private StockInboundMapper stockInboundMapper;

    @Autowired
    private StockOutboundMapper stockOutboundMapper;

    @Autowired
    private SysUserShopMapper userShopMapper;

    /**
     * 查询退货入库列表
     *
     * @param stockReturn 退货入库
     * @return 退货入库
     */
    @Override
    public List<StockReturn> selectStockReturnList(StockReturn stockReturn) {
        Long userId = SecurityUtils.getUserId();

        // 管理员查看全部
        if (userId != null && userId == 1L) {
            return stockReturnMapper.selectStockReturnList(stockReturn);
        }

        // 普通用户根据店铺过滤
        List<Long> shopIds = userShopMapper.selectShopIdsByUserId(userId);
        if (shopIds == null || shopIds.isEmpty()) {
            return new ArrayList<>();
        }

        // 设置店铺ID过滤条件（支持多店铺）
        stockReturn.getParams().put("shopIdList", shopIds);

        return stockReturnMapper.selectStockReturnList(stockReturn);
    }

    /**
     * 查询退货入库详细信息
     *
     * @param returnId 退货入库ID
     * @return 退货入库
     */
    @Override
    public StockReturn selectStockReturnByReturnId(Long returnId) {
        // 查询退货入库
        StockReturn stockReturn = stockReturnMapper.selectStockReturnByReturnId(returnId);

        if (stockReturn == null) {
            return null;
        }

        Long userId = SecurityUtils.getUserId();

        // 管理员可以查看全部
        if (userId != null && userId == 1L) {
            return stockReturn;
        }

        // 普通用户需要验证店铺权限
        List<Long> shopIds = userShopMapper.selectShopIdsByUserId(userId);
        if (shopIds == null || !shopIds.contains(stockReturn.getShopId())) {
            return null; // 无权限
        }

        return stockReturn;
    }

    /**
     * 新增退货入库
     *
     * @param stockReturn 退货入库
     * @return 结果
     */
    @Override
    @Transactional
    public int insertStockReturn(StockReturn stockReturn) {
        // 查询关联的出库记录，获取SKU、产品名称、店铺ID等信息
        StockOutbound outbound = stockOutboundMapper.selectStockOutboundList(new StockOutbound() {{
            setOutboundId(stockReturn.getSourceOutboundId());
        }}).stream().findFirst().orElse(null);

        if (outbound == null) {
            throw new RuntimeException("关联的出库记录不存在");
        }

        // 自动填充信息
        stockReturn.setSku(outbound.getSku());
        stockReturn.setProductName(outbound.getProductName());
        stockReturn.setShopId(outbound.getShopId());

        // 设置创建者
        stockReturn.setCreateBy(SecurityUtils.getUsername());
        stockReturn.setDelFlag("0");

        // 插入退货记录
        int result = stockReturnMapper.insertStockReturn(stockReturn);

        // 同步插入库存入库记录（类型为RETURN）
        if (result > 0) {
            StockInbound stockInbound = new StockInbound();
            stockInbound.setSku(stockReturn.getSku());
            stockInbound.setProductName(stockReturn.getProductName());
            stockInbound.setShopId(stockReturn.getShopId());
            stockInbound.setInboundQuantity(stockReturn.getReturnQuantity());
            stockInbound.setInboundType("RETURN");
            stockInbound.setSourceId(stockReturn.getReturnId()); // 关联退货记录ID
            stockInbound.setInboundDate(stockReturn.getReturnDate());
            stockInbound.setRemark("退货入库：" + (stockReturn.getRemark() != null ? stockReturn.getRemark() : ""));
            stockInbound.setDelFlag("0");
            stockInbound.setCreateBy(SecurityUtils.getUsername());

            stockInboundMapper.insertStockInbound(stockInbound);
        }

        return result;
    }

    /**
     * 修改退货入库
     *
     * @param stockReturn 退货入库
     * @return 结果
     */
    @Override
    @Transactional
    public int updateStockReturn(StockReturn stockReturn) {
        // 数据权限检查
        StockReturn existingReturn = selectStockReturnByReturnId(stockReturn.getReturnId());
        if (existingReturn == null) {
            return 0; // 无权限或记录不存在
        }

        // 设置更新者
        stockReturn.setUpdateBy(SecurityUtils.getUsername());

        // 在更新前保存原始数据用于匹配孤立库存记录
        StockReturn originalData = existingReturn;

        // 更新退货记录
        int result = stockReturnMapper.updateStockReturn(stockReturn);

        // 同步更新库存入库记录（兼容新旧数据）
        if (result > 0) {
            // 准备更新数据
            StockInbound stockInbound = new StockInbound();
            stockInbound.setSourceId(stockReturn.getReturnId());
            stockInbound.setInboundType("RETURN");
            stockInbound.setSku(stockReturn.getSku());
            stockInbound.setProductName(stockReturn.getProductName());
            stockInbound.setShopId(stockReturn.getShopId());
            stockInbound.setInboundQuantity(stockReturn.getReturnQuantity());
            stockInbound.setInboundDate(stockReturn.getReturnDate());
            stockInbound.setRemark("退货入库：" + (stockReturn.getRemark() != null ? stockReturn.getRemark() : ""));
            stockInbound.setUpdateBy(SecurityUtils.getUsername());

            // 先尝试通过 source_id 更新（新数据）
            int updateCount = stockInboundMapper.updateStockInboundBySourceId(stockInbound);

            // 如果没有更新任何记录，说明可能是旧数据（source_id 为空），尝试智能匹配
            if (updateCount == 0 && originalData != null) {
                // 使用更新前的原始数据在 SQL 层面精确匹配孤立的库存记录
                // 避免内存中遍历所有孤立记录，提升性能
                StockInbound orphan = stockInboundMapper.selectOrphanStockInboundByOriginalData(
                    "RETURN",
                    originalData.getSku(),              // 使用修改前的原始SKU
                    originalData.getReturnQuantity(),   // 使用修改前的原始数量
                    originalData.getReturnDate(),       // 使用修改前的原始日期
                    originalData.getCreateBy()          // 使用原始创建人
                );

                if (orphan != null) {
                    // 找到匹配的孤立记录，建立关联并更新为新数据
                    orphan.setSourceId(stockReturn.getReturnId());
                    orphan.setSku(stockReturn.getSku());
                    orphan.setProductName(stockReturn.getProductName());
                    orphan.setShopId(stockReturn.getShopId());
                    orphan.setInboundQuantity(stockReturn.getReturnQuantity());
                    orphan.setInboundDate(stockReturn.getReturnDate());
                    orphan.setRemark("退货入库：" + (stockReturn.getRemark() != null ? stockReturn.getRemark() : ""));
                    orphan.setUpdateBy(SecurityUtils.getUsername());

                    stockInboundMapper.updateStockInbound(orphan);
                }
            }
        }

        return result;
    }

    /**
     * 批量删除退货入库
     *
     * @param returnIds 需要删除的退货入库ID数组
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteStockReturnByReturnIds(Long[] returnIds) {
        // 数据权限检查
        for (Long returnId : returnIds) {
            StockReturn stockReturn = selectStockReturnByReturnId(returnId);
            if (stockReturn == null) {
                return 0; // 无权限或记录不存在
            }
        }

        // 删除退货记录（软删除）
        int result = stockReturnMapper.deleteStockReturnByReturnIds(returnIds);

        // 同步删除对应的库存入库记录（RETURN类型）
        // 注意：需要删除inbound_type='RETURN'且source_id为returnId的记录
        if (result > 0) {
            // 使用deleteStockInboundBySourceIds批量删除
            stockInboundMapper.deleteStockInboundByReturnSourceIds(returnIds);
        }

        return result;
    }

    /**
     * 判断两个日期是否是同一天
     *
     * @param date1 日期1
     * @param date2 日期2
     * @return 是否同一天
     */
    private boolean isSameDay(java.util.Date date1, java.util.Date date2) {
        if (date1 == null || date2 == null) {
            return false;
        }
        java.util.Calendar cal1 = java.util.Calendar.getInstance();
        cal1.setTime(date1);
        java.util.Calendar cal2 = java.util.Calendar.getInstance();
        cal2.setTime(date2);
        
        return cal1.get(java.util.Calendar.YEAR) == cal2.get(java.util.Calendar.YEAR)
            && cal1.get(java.util.Calendar.DAY_OF_YEAR) == cal2.get(java.util.Calendar.DAY_OF_YEAR);
    }
}

